<template>
  <div class="w-full flex-1 flex flex-col">
    <div class="table-wrapper flex-1">
      <!-- 当提供了maxHeight时，不使用auto-resizer -->
      <template v-if="props.maxHeight">
        <el-table v-bind="$attrs" ref="tableRef" class="table-container" :max-height="props.maxHeight" width="100%"
          @selection-change="selectChange" @select="selectBox" @select-all="selectAll">
            <template v-for="(item, index) in props.tableTitle" :key="index">
              <!-- 展开项 -->
              <el-table-column v-if="item.type && item.type == 'expand'" type="expand">
                <template #default="props">
                  <slot name="expand" :data="props"></slot>
                </template>
              </el-table-column>
              <!-- 选择框 -->
              <el-table-column :fixed="item.fixed || false" v-if="item.type && item.type == 'selection'"
                type="selection" :width="item.width" :selectable="(row: any) => {
                  if (item.fn) {
                    return item.fn(row)
                  } else {
                    return true
                  }
                }" />
              <!-- 序号 -->
              <el-table-column :fixed="item.fixed || false" v-if="item.type && item.type == 'index'" type="index"
                :width="item.width || '80'" label="序号" :align="item?.align ? item.align : 'left'"
                :headerAlign="item.headerAlign ? item.headerAlign : 'left'"></el-table-column>
              <!-- Text列表 -->
              <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                :prop="item.prop" v-if="item.type && item.type == 'text'" :align="item?.align ? item.align : 'left'"
                :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'"
                :show-overflow-tooltip="item.showOverflowTooltip || false">
                <template #default="{ row }">
                  <span v-if="
                    (row[item.prop] == null || row[item.prop] == '') &&
                    row[item.prop] != 0
                  ">--</span>
                  <span v-else>{{ row[item.prop] }}</span>
                </template>
              </el-table-column>
              <!-- 时间列表 -->
              <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                :prop="item.prop" v-if="item.type && item.type == 'time'" :align="item?.align ? item.align : 'left'"
                :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                <template #default="{ row }">
                  <span v-if="
                    (row[item.prop] == null || row[item.prop] == '') &&
                    row[item.prop] != 0
                  ">--</span>
                  <span v-else>{{ formatTime(row[item.prop]) }}</span>
                </template>
              </el-table-column>
              <!-- 状态栏列表 -->
              <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                :prop="item.prop" v-if="item.type && item.type == 'status'" :align="item?.align ? item.align : 'left'"
                :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                <template #default="{ row }">
                  <el-link :type="item.options.find((v: any) => v.value == row[item.prop])?.type">
                    {{item.options.find((v: any) => v.value == row[item.prop])?.text}}
                  </el-link>
                </template>
              </el-table-column>
              <!-- switch -->
              <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                :prop="item.prop" v-if="item.type && item.type == 'switch'" :align="item?.align ? item.align : 'left'"
                :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                <template #default="{ row }">
                  <el-switch v-model="row[item.prop]" :loading="row.loading" :active-value="item.activeValue || '0'"
                    :inactive-value="item.inactiveValue || '9'" @change="(val: any) => item.click(val, row)" />
                </template>
              </el-table-column>
              <!-- 图片展示列表 -->
              <el-table-column v-if="item.type && item.type == 'image'" :fixed="item.fixed" :label="item.label"
                :width="item?.width ? item?.width : ''" :align="item?.align ? item?.align : 'left'"
                :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                <template #default="{ row }">
                  <div v-if="row[item.prop]" style="display: flex; justify-content: left">
                    <div v-if="Array.isArray(row[item.prop])" style="
                  display: flex;
                  flex-wrap: wrap;
                  justify-content: center;
                  width: 100%;
                ">
                      <el-image style="width: 50px; margin: 5px" v-for="it in row[item.prop]" @click="
                        handlePictureCardPreview(
                          baseUrl + '/oss/file/preview?fileName=' + it
                        )
                        " :style="item.style" :src="baseUrl + '/oss/file/preview?fileName=' + it" />
                    </div>
                    <div v-else>
                      <el-image @click="
                        handlePictureCardPreview(
                          baseUrl + '/oss/file/preview?fileName=' + row[item.prop]
                        )
                        " :style="item.style" :src="baseUrl + '/oss/file/preview?fileName=' + row[item.prop]" />
                    </div>
                  </div>
                  <span v-else style="font-size: 10px">暂未上传图片</span>
                </template>
              </el-table-column>
              <!-- 动态自定义内容列表 -->
              <el-table-column v-if="item.type && item.type == 'custom'" :fixed="item.fixed" :label="item.label"
                :width="item?.width ? item?.width : ''" :align="item?.align ? item?.align : 'left'"
                :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                <template #default="{ row, column, $index }">
                  <slot :name="item.name" :data="{ row, column, $index }"></slot>
                </template>
              </el-table-column>
              <!-- 操作列表 -->
              <el-table-column v-if="item.type && item.type == 'operate'" :fixed="item.fixed" :label="item.label"
                :width="item?.width ? item?.width : ''" :align="item?.align ? item?.align : 'left'"
                :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                <template #default="{ row, column }">
                  <el-button @click="() => v.click(row, column)" :type="v.type" :size="v.size ? v.size : 'mini'"
                    v-for="(v, i) in item.actions.filter((v: any) => !v.isLink)" :key="i">
                    {{ v.name }}
                  </el-button>
                  <template v-for="(v, i) in item.actions.filter((v: any) => v.isLink)" :key="i">
                    <div style="margin: 0 5px; display: inline-block" class="father pr-2" v-permission-button="'1'"
                      v-if="v.name !== '删除' && v.name !== '触发器' && (v.show ? v.show(row) : true)">
                      <el-link @click="() => v.click(row, column)" :type="v.type"
                        :style="v.style ? v.style(row) : null">
                        {{ v.name }}
                      </el-link>
                    </div>
                    <!-- 触发器单独处理 -->
                    <div style="margin: 0 5px; display: inline-block" v-if="v.name !== '删除' && v.name == '触发器'">
                      <el-link @click="() => v.click(row, column)" :type="v.type" :style="v.style">
                        {{v.options.find((f: any) => f.value == row[v.prop])?.text}}
                      </el-link>
                    </div>
                    <!-- 删除 -->
                    <div style="margin: 0 5px; display: inline-block"
                      v-if="v.name == '删除' && (v.showDel ? v.showDel(row) : true)">
                      <el-link v-if="v.notNeedAuto" @click="() => v.click(row, column)" :type="v.type"
                        :style="v.style ? v.style(row) : null">
                        {{ v.name }}
                      </el-link>
                      <el-link v-else @click="() => openDelDialog(row, !!v.userInfo)" :type="v.type" :style="v.style">
                        {{ v.name }}
                      </el-link>
                    </div>
                  </template>
                </template>
              </el-table-column>
            </template>
        </el-table>
      </template>
      <!-- 当没有提供maxHeight时，使用auto-resizer -->
      <template v-else>
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table v-bind="$attrs" ref="tableRef" class="table-container" :max-height="height" :width="width"
              @selection-change="selectChange" @select="selectBox" @select-all="selectAll">
              <template v-for="(item, index) in props.tableTitle" :key="index">
                <!-- 展开项 -->
                <el-table-column v-if="item.type && item.type == 'expand'" type="expand">
                  <template #default="props">
                    <slot name="expand" :data="props"></slot>
                  </template>
                </el-table-column>
                <!-- 选择框 -->
                <el-table-column :fixed="item.fixed || false" v-if="item.type && item.type == 'selection'"
                  type="selection" :width="item.width" :selectable="(row: any) => {
                    if (item.fn) {
                      return item.fn(row)
                    } else {
                      return true
                    }
                  }" />
                <!-- 序号 -->
                <el-table-column :fixed="item.fixed || false" v-if="item.type && item.type == 'index'" type="index"
                  :width="item.width || '80'" label="序号" :align="item?.align ? item.align : 'left'"
                  :headerAlign="item.headerAlign ? item.headerAlign : 'left'"></el-table-column>
                <!-- Text列表 -->
                <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                  :prop="item.prop" v-if="item.type && item.type == 'text'" :align="item?.align ? item.align : 'left'"
                  :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'"
                  :show-overflow-tooltip="item.showOverflowTooltip || false">
                  <template #default="{ row }">
                    <span v-if="
                      (row[item.prop] == null || row[item.prop] == '') &&
                      row[item.prop] != 0
                    ">--</span>
                    <span v-else>{{ row[item.prop] }}</span>
                  </template>
                </el-table-column>
                <!-- 时间列表 -->
                <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                  :prop="item.prop" v-if="item.type && item.type == 'time'" :align="item?.align ? item.align : 'left'"
                  :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                  <template #default="{ row }">
                    <span v-if="
                      (row[item.prop] == null || row[item.prop] == '') &&
                      row[item.prop] != 0
                    ">--</span>
                    <span v-else>{{ formatTime(row[item.prop]) }}</span>
                  </template>
                </el-table-column>
                <!-- 状态栏列表 -->
                <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                  :prop="item.prop" v-if="item.type && item.type == 'status'" :align="item?.align ? item.align : 'left'"
                  :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                  <template #default="{ row }">
                    <el-link :type="item.options.find((v: any) => v.value == row[item.prop])?.type">
                      {{item.options.find((v: any) => v.value == row[item.prop])?.text}}
                    </el-link>
                  </template>
                </el-table-column>
                <!-- switch -->
                <el-table-column :fixed="item.fixed || false" :label="item.label" :sortable="item.sortable"
                  :prop="item.prop" v-if="item.type && item.type == 'switch'" :align="item?.align ? item.align : 'left'"
                  :width="item?.width ? item?.width : ''" :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                  <template #default="{ row }">
                    <el-switch v-model="row[item.prop]" :loading="row.loading" :active-value="item.activeValue || '0'"
                      :inactive-value="item.inactiveValue || '9'" @change="(val: any) => item.click(val, row)" />
                  </template>
                </el-table-column>
                <!-- 图片展示列表 -->
                <el-table-column v-if="item.type && item.type == 'image'" :fixed="item.fixed" :label="item.label"
                  :width="item?.width ? item?.width : ''" :align="item?.align ? item?.align : 'left'"
                  :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                  <template #default="{ row }">
                    <div v-if="row[item.prop]" style="display: flex; justify-content: left">
                      <div v-if="Array.isArray(row[item.prop])" style="
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: center;
                    width: 100%;
                  ">
                        <el-image style="width: 50px; margin: 5px" v-for="it in row[item.prop]" @click="
                          handlePictureCardPreview(
                            baseUrl + '/oss/file/preview?fileName=' + it
                          )
                          " :style="item.style" :src="baseUrl + '/oss/file/preview?fileName=' + it" />
                      </div>
                      <div v-else>
                        <el-image @click="
                          handlePictureCardPreview(
                            baseUrl + '/oss/file/preview?fileName=' + row[item.prop]
                          )
                          " :style="item.style" :src="baseUrl + '/oss/file/preview?fileName=' + row[item.prop]" />
                      </div>
                    </div>
                    <span v-else style="font-size: 10px">暂未上传图片</span>
                  </template>
                </el-table-column>
                <!-- 动态自定义内容列表 -->
                <el-table-column v-if="item.type && item.type == 'custom'" :fixed="item.fixed" :label="item.label"
                  :width="item?.width ? item?.width : ''" :align="item?.align ? item?.align : 'left'"
                  :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                  <template #default="{ row, column, $index }">
                    <slot :name="item.name" :data="{ row, column, $index }"></slot>
                  </template>
                </el-table-column>
                <!-- 操作列表 -->
                <el-table-column v-if="item.type && item.type == 'operate'" :fixed="item.fixed" :label="item.label"
                  :width="item?.width ? item?.width : ''" :align="item?.align ? item?.align : 'left'"
                  :headerAlign="item.headerAlign ? item.headerAlign : 'left'">
                  <template #default="{ row, column }">
                    <el-button @click="() => v.click(row, column)" :type="v.type" :size="v.size ? v.size : 'mini'"
                      v-for="(v, i) in item.actions.filter((v: any) => !v.isLink)" :key="i">
                      {{ v.name }}
                    </el-button>
                    <template v-for="(v, i) in item.actions.filter((v: any) => v.isLink)" :key="i">
                      <div style="margin: 0 5px; display: inline-block" class="father pr-2" v-permission-button="'1'"
                        v-if="v.name !== '删除' && v.name !== '触发器' && (v.show ? v.show(row) : true)">
                        <el-link @click="() => v.click(row, column)" :type="v.type"
                          :style="v.style ? v.style(row) : null">
                          {{ v.name }}
                        </el-link>
                      </div>
                      <!-- 触发器单独处理 -->
                      <div style="margin: 0 5px; display: inline-block" v-if="v.name !== '删除' && v.name == '触发器'">
                        <el-link @click="() => v.click(row, column)" :type="v.type" :style="v.style">
                          {{v.options.find((f: any) => f.value == row[v.prop])?.text}}
                        </el-link>
                      </div>
                      <!-- 删除 -->
                      <div style="margin: 0 5px; display: inline-block"
                        v-if="v.name == '删除' && (v.showDel ? v.showDel(row) : true)">
                        <el-link v-if="v.notNeedAuto" @click="() => v.click(row, column)" :type="v.type"
                          :style="v.style ? v.style(row) : null">
                          {{ v.name }}
                        </el-link>
                        <el-link v-else @click="() => openDelDialog(row, !!v.userInfo)" :type="v.type" :style="v.style">
                          {{ v.name }}
                        </el-link>
                      </div>
                    </template>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </template>
        </el-auto-resizer>
      </template>

    </div>

    <!-- 分页栏 -->
    <div v-if="props.showPagination && pageConfig" class="pageConfig flex-shrink-0">
      <el-pagination :current-page="pageConfig.currentPage" :page-size="pageConfig.pageSize"
        :page-sizes="pageConfig.pageSizes" :small="pageConfig.small || false" :disabled="pageConfig.disabled || false"
        :background="pageConfig.background" :layout="pageConfig.layout" :total="parseInt(pageConfig.total as any, 10)"
        @size-change="(e: any) => pageConfig?.handleSizeChange(e)"
        @current-change="(e: any) => pageConfig?.handleCurrentChange(e)" />
    </div>

    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible">
      <div style="width: 90%; margin: 0 auto">
        <img style="width: 100%" :src="dialogImageUrl" alt="预览图片" />
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <auto-del ref="delRef" :delMethod="props?.delMethod" :refreshMethod="props?.refreshMethod"
      :itemType="props?.itemType" />
  </div>
</template>

<script setup lang="ts">
import autoDel from '@/components/delDialog/index.vue'
import { useAttrs, computed, ref, watch } from 'vue'
import { error } from '@/utils/toast'

// 接口定义
export interface PageConfigType {
  currentPage: number
  pageSize: number
  pageSizes: Array<number>
  layout: string
  total: number | string
  background: boolean
  disabled?: boolean
  small?: boolean
  handleSizeChange: Function | any
  handleCurrentChange: Function | any
  [key: string]: any
}

// 基础变量
const $attr = useAttrs()
const baseUrl = import.meta.env.VITE_RESOURCE_URL
console.log('ElementTable baseUrl:', baseUrl, 'NODE_ENV:', import.meta.env.NODE_ENV, 'MODE:', import.meta.env.MODE)

// Props定义
const props = withDefaults(
  defineProps<{
    tableTitle: Array<Object | any>
    showPagination?: boolean
    // 删除方法
    delMethod?: Function
    // 刷新方法
    refreshMethod?: Function
    // 删除参数特殊处理(不传默认是当前行的id)
    delParams?: Function
    // 项目类型，用于删除确认对话框
    itemType?: string
    pageConfig?: Partial<PageConfigType>
    // 表格最大高度
    maxHeight?: number | string
  }>(),
  {
    showPagination: true,
    itemType: '项目'
  }
)

// 响应式变量
const delRef = ref<any>(null)
const dialogVisible = ref<boolean>(false)
const dialogImageUrl = ref<string>('')
const tableRef = ref<any>()

// 计算属性
const pageConfig = computed(() => props.pageConfig)

// 事件处理函数
const emits = defineEmits(['selectChange', 'selectBox', 'selectAll'])

const selectChange = (val: any) => {
  emits('selectChange', val)
}

const selectBox = (selection: any, row: any) => {
  emits('selectBox', selection, row)
}

const selectAll = (selection: any) => {
  emits('selectAll', selection)
}

const handlePictureCardPreview = (url: string) => {
  dialogImageUrl.value = url
  dialogVisible.value = true
}

// 时间格式化函数
const formatTime = (date: any) => {
  if (!date) return '--'
  return new Date(date).toLocaleString()
}

// 删除相关函数
const openDelDialog = (row: any, user: any) => {
  console.log('fkfkkfkfkfk', row)
  if (user) {
    let orgObj = JSON.parse(localStorage.getItem('userBaseInfo')!).userBaseInfo
    if (orgObj.userId == row.userId) {
      error('不能删除自己的账号')
      return
    }
  }
  // 处理删除弹窗参数
  let param = null
  // 特殊处理
  if (props.delParams) {
    param = props.delParams(row)
  } else {
    // 否则默认传id
    param = row.id
  }
  delRef.value.open(param)
}

// 工具函数
const clearSelectionFun = () => {
  tableRef.value?.clearSelection()
}

const toggleRowSelectionFun = (row: any, boolean: boolean) => {
  tableRef.value?.toggleRowSelection(row, boolean)
}

// 监听器
watch(
  () => $attr.data,
  (val: any) => {
    if (props.tableTitle.find((it: any) => it.type == 'switch')) {
      val.forEach((item: any) => {
        item.loading = false
      })
    }
  }
)

// 暴露给父组件的方法
defineExpose({
  clearSelectionFun,
  toggleRowSelectionFun
})
</script>

<style lang="scss" scoped>
.pageConfig {
  width: 100%;
  margin-top: 15px;
  padding: 15px 0;
  display: flex;
  justify-content: right;
  flex-shrink: 0;
}

.table-wrapper {
  min-height: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.table-container {
  flex: 1;
  width: 100%;
  overflow: auto;
}

.el-table {
  width: 100%;

  :deep(.is-leaf) {
    background-color: #f8f8f8;
    color: #333;
  }

  :deep(.el-table__cell) {
    //     text-align: left;
    // text-align: left !important;
  }
}

:deep(.left) {
  text-align: left !important;
}

:deep(.is-leaf) {
  background-color: #f8f8f8 !important;
}

.el-pagination {
  :deep(.is-active) {
    background-color: #e5eeff !important;
    color: #3665ff !important;
  }

  :deep(.el-pagination__total) {
    font-size: 16px !important;
    font-weight: 600 !important;
  }
}

.el-table {
  --el-table-header-bg-color: #f8f8f8 !important;

  .father {
    position: relative;

    .borr {
      &::after {
        content: '';
        position: absolute;
        height: 8px;
        width: 1px;
        right: 1px;
        top: 50%;
        border-right: 1px solid #cccccc;
        transform: translateY(-50%);
      }
    }
  }
}
</style>